package Haak::C::Default;

use strict;
use warnings;
use base qw( Haak );

use Encode ();
use DateTime;
use Path::Class ();
use POSIX ();
use Data::Dumper;
use POE::Component::IKC::ClientLite;
sub do_default {
    my $self = shift;

    my $irclog  = $self->config->{irclog};
    my $date = $self->path_args->[1] || '';
    if ($date =~ /^([0-9]{4})-([0-9][0-9])-([0-9][0-9])$/) {
        my $epoch = DateTime->new(
				  year      => $1,
				  month     => $2,
				  day       => $3,
				  time_zone => 'Asia/Seoul',
				  )->epoch;
	
        $self->stash->{prev_date} = POSIX::strftime("%Y-%m-%d", localtime($epoch - (24*60*60) ));
        $self->stash->{next_date} = POSIX::strftime("%Y-%m-%d", localtime($epoch + (24*60*60) ));
    } else {
        $date = POSIX::strftime("%Y-%m-%d", localtime);
        $self->stash->{prev_date} = POSIX::strftime("%Y-%m-%d", localtime(time - (24*60*60) ));
        $self->stash->{next_date} = POSIX::strftime("%Y-%m-%d", localtime(time + (24*60*60) ));
    }
    $self->stash->{date} = $date;

    my $logfile = "$date.log";
    my $path = $self->path_args->[0] || "perl-kr";
    $self->stash->{path} = $path;
    my $logdir = Path::Class::dir( $irclog.$path );

    my $histories;
    my @data;
    while (my $dir = $logdir->next) {
        my $logpath = "$dir/$logfile";
        next unless -f $logpath;
	$histories = Path::Class::file($logpath)->slurp;
    }
    $self->stash->{histories} = [ split /\n/, $histories ];
    $self->stash->{time} = POSIX::strftime('%H%M%S', localtime);
}

sub do_getmsg {
    my $self = shift;

    my $irc_log = $self->config->{irclog};

    my $today = POSIX::strftime("%Y-%m-%d", localtime);

    my @histories = split /\n/, Path::Class::file($irc_log.'perl-kr'.'/'."$today.log")->slurp;

    my $time_set = $self->req->param('time');
    my @data;
    foreach my $comment (@histories) {
	my ($when, $what) = $comment =~ /^\[([^]]+)\] (.+)$/;
	$when =~ s/\://g;
	if ($when && $when > $time_set) {
	    push @data, { when => $when, what => $what };
	}
    }

    $self->stash->{data} = \@data;
    $self->set_view('JSON');
}

sub do_send_msg {
    my $self = shift;
    
    $self->res->content_type('text/html');
    $self->res->body('');
    my $author = $self->req->param('author') || return;
    my $msg = $self->req->param('msg') || return;

    my $text = "<".$author."> [ Web ] ".$msg;
 
    my $name = "Client$$";
    my $remote = create_ikc_client(
        port => 31338,
        name => $name,
        timeout => 1,
	);
    return unless $remote;
    my $return_value = $remote->post_respond( 'application/update', $text );
    return unless defined $return_value;
}
1;

=head1 NAME

Haak::C::Default - Soozy Component

=head1 SYNOPSIS

See L<Haak>

=head1 DESCRIPTION

Soozy Component

=head1 AUTHOR

JEEN

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut
